<template>
    <div class="app-container">
      <el-card class="box-card clearfix">
        <!-- title -->
        <el-row class="elrow">
          <el-col :span="24"><div class="grid-content bg-purple-dark">
            <span class='container'>说明：目前支持学科和关键字条件筛选</span>
              <el-button style="float: right" type="success" size="small" @click="$router.push('/questions/new')">
                <i class="el-icon-edit"></i>
                新增试题
            </el-button>
          </div></el-col>
        </el-row>

        <!-- 搜索 -->
        <el-form :model="ruleForm" ref="ruleForm" label-width="80px">
          <el-row>
            <el-col :span="6">
              <el-form-item label="学科" prop='subjectID'>
                <el-select v-model="ruleForm.subjectID" placeholder="请选择" style="width:240px">
                  <el-option :label="item.subjectName" :value="item.id" v-for="item in subjectName" :key="item.id"
                  @click.native='clickoPtion(item.id)'></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="二级目录" prop='catalogID'>
                <el-select v-model="ruleForm.catalogID" placeholder="请选择" style="width:240px">
                  <el-option :label="item.label" :value="item.value" v-for="item in simpleList" :key="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="标签" prop='tags'>
                <el-select v-model="ruleForm.tags" placeholder="请选择" style="width:240px">
                  <el-option :label="item.label" :value="item.value" v-for="item in getSimpleList" :key="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="关键字" prop='keyword'>
                <el-input v-model="ruleForm.keyword" placeholder="根据题干搜索" style="width:230px"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="试题类型" prop='questionType'>
                <el-select v-model="ruleForm.questionType" placeholder="请选择" style="width:240px">
                  <el-option :label="item.label" :value="item.value" v-for="item in questionTypeList" :key="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="难度" prop='difficulty'>
                <el-select v-model="ruleForm.difficulty" placeholder="请选择" style="width:240px">
                  <el-option :label="item.label" :value="item.value" v-for="item in difficultyList" :key="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="方向" prop='direction'>
                <el-select v-model="ruleForm.direction" placeholder="请选择" style="width:240px">
                  <el-option :label="item" :value="item" v-for="(item,i) in directionList" :key="i"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="录用人" prop='creatorID'>
                <el-select v-model="ruleForm.creatorID" placeholder="请选择" style="width:230px">
                  <el-option :label="item.username" :value="item.username" v-for="item in nameist" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="题目备注" prop='remarks'>
                <el-input v-model="ruleForm.remarks"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="企业简称" prop='shortName'>
                <el-input v-model="ruleForm.shortName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="城市" prop='city'>
                <el-select v-model="ruleForm.city" placeholder="请选择" style="width:120px">
                  <el-option :label="item" :value="item" v-for="item in provincesList" :key="item"
                  @click.native='clickProvinces(item)'></el-option>
                </el-select>
                <el-select v-model="ruleForm.province" placeholder="请选择" style="width:120px">
                  <el-option :label="item" :value="item" v-for="item in citysList" :key="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item>
                <el-button size="small" @click="empty">清除</el-button>
                <el-button type="primary"  size="small" @click="search">搜索</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- Tab栏 -->
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick" class="tabs">
          <!-- 消息提示 -->
          <el-alert
            :title="title"
            type="info"
            show-icon>
          </el-alert>
          <el-tab-pane label="全部" name="first"></el-tab-pane>
          <el-tab-pane label="待审核" name="second"></el-tab-pane>
          <el-tab-pane label="已审核" name="third"></el-tab-pane>
          <el-tab-pane label="已拒绝" name="fourth"></el-tab-pane>
        </el-tabs>

        <!-- 表单 -->
        <el-table
        :header-cell-style="{background:'#FAFAFA'}"
        :data="tableData"
        style="width: 100%;height:100%">
        <el-table-column
          v-for="(item,i) in arr"
          :key="item"
          :prop="hand[i]"
          :label="item"
          heigth="150"
          :width="width[i]">
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="200">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="preview(scope.row)">预览</el-button>
            <el-button type="text" size="small" :disabled="scope.row.chkState !== '待审核'" @click="audit(scope.row)">审核</el-button>
            <el-button type="text" size="small" @click="alter(scope.row)" :disabled="scope.row.publishState === '已发布'">修改</el-button>
            <el-button type="text" size="small" @click="clikcEmit(scope.row)">{{ scope.row.publishState === '已发布' ? '下架':'上架' }}</el-button>
            <el-button type="text" size="small" :disabled="scope.row.publishState === '已发布'" @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
        </el-table>

      <!-- 分页 -->
      <el-row style="float: right" class="row">
        <el-col>
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="prev, pager, next, sizes, jumper"
            :page-size="pagesize"
            :page-sizes="[2, 10, 20, 50]"
            :current-page="page"
            :total="counts">
          </el-pagination>
        </el-col>
      </el-row>
      </el-card>

      <!-- Dialog 审核 -->
      <el-dialog
        title="题目审核"
        :visible.sync="auditDialog"
        @close='dialogaudit'
        width="25%">
          <el-radio-group v-model="chkState">
            <el-radio label="1">通过</el-radio>
            <el-radio label="2">拒绝</el-radio>
          </el-radio-group>
          <div class="textarea">
            <el-input type="textarea" v-model="chkRemarks" placeholder="请输入审核意见"></el-input>
          </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogaudit">取 消</el-button>
          <el-button type="primary" @click="clickAudit">确 定</el-button>
        </span>
      </el-dialog>

      <!-- Dialog 预览 -->
      <el-dialog
        title="题目预览"
        :visible.sync="previewDialog"
        @close='previewListDialog'
        width="60%">
          <el-row class="elrow">
            <el-col :span="6">
              <span>【题型】：</span> {{previewList.questionType}}题
            </el-col>
            <el-col :span="6">
              <span>【编号】：</span> {{previewList.id}}
            </el-col>
            <el-col :span="6">
              <span>【难度】：</span> {{previewList.difficulty}}
            </el-col>
            <el-col :span="6">
              <span>【标签】：</span> {{previewList.tags}}
            </el-col>
          </el-row>
          <el-row class="elrow">
            <el-col :span="6">
              <span>【学科】：</span> {{previewList.subject}}
            </el-col>
            <el-col :span="6">
              <span>【目录】：</span> {{previewList.catalog}}
            </el-col>
            <el-col :span="6">
              <span>【方向】：</span> {{previewList.direction}}
            </el-col>
          </el-row>
          <hr>
          <el-row>
            <el-col :span="6">
              <span>【题干】：</span>
              <p>{{previewList.question}}</p>
            </el-col>
          <el-col>{{previewList.questionType}}题 选项：（以下选中的选项为正确答案）</el-col>
          <el-col class="elradio" v-for="item in previewList.options" :key="item.id">
            <el-radio :label="item.title" v-model="optionsList"></el-radio>
          </el-col>
          </el-row>
          <hr>
          <el-row class="elradio">
            <el-col :span="6">
              <span>【参考答案】：</span>
              <span><el-button type="danger" size="small" @click="showVideo = !showVideo">视频答案预览</el-button></span>
              <div style="width:400px;height:300px;padding:10px 0;" v-if="showVideo">
                <video autoplay="autoplay" controls="controls" :src="previewList.videoURL" style="width:100%;height:100%"></video>
              </div>
            </el-col>
          </el-row>
          <hr>
          <el-row class="elradio">
            <el-col :span="6">
              <span>【答案解析】：{{previewList.answer}}</span>
            </el-col>
          </el-row>
          <hr>
          <el-row class="elradio">
            <el-col :span="6">
              <span>【题目备注】：{{previewList.remarks}}</span>
            </el-col>
          </el-row>
        <span slot="footer" class="dialog-footer">
          <el-button @click="previewListDialog" type="primary">关闭</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
import { choice, choiceCheck, choicePublish, choiceAdd, detail } from '@/api/hmmm/questions'
import { parseTime, html2Text } from '@/utils/index'
import { difficulty, questionType, publishType, questionType as question, direction } from '@/api/hmmm/constants'
import { list } from '@/api/hmmm/subjects'
import { simple } from '@/api/hmmm/directorys'
import { simple as getSimple } from '@/api/hmmm/tags'
import { provinces, citys } from '@/api/hmmm/citys'
import { list as getList } from '@/api/base/users'

export default {
  data () {
    return {
      ruleForm: {
        subjectID: '',
        catalogID: '',
        tags: '',
        keyword: '',
        questionType: '',
        difficulty: '',
        direction: '',
        creatorID: '',
        remarks: '',
        shortName: '',
        city: '',
        province: ''
      },
      tableData: [],
      activeName: 'first',
      title: '',
      arr: ['试题编号', '学科', '目录', '题型', '题干', '录入时间', '难度', '录用人', '审核状态', '审核意见', '审核人', '发布状态'],
      hand: ['number', 'subject', 'catalog', 'questionType', 'question', 'addDate', 'difficulty', 'creator', 'chkState', 'chkRemarks', 'chkUser', 'publishState'],
      page: 1,
      pagesize: 10,
      counts: 1,
      width: ['120', '120', '120', '120', '200', '200', '120', '120', '120', '120', '120'],
      state: ['待审核', '已审核', '已拒绝'],
      auditDialog: false,
      previewDialog: false,
      chkState: '',
      chkRemarks: '',
      auditId: '',
      previewList: [],
      optionsList: '',
      showVideo: false,
      subjectName: [],
      simpleList: [],
      getSimpleList: [],
      questionTypeList: question,
      difficultyList: difficulty,
      directionList: direction,
      nameist: [],
      provincesList: [],
      citysList: [],
      inputShow: false
    }
  },
  created () {
    this.getRuleForm()
    this.getList()
  },
  methods: {
    // Tab切换
    handleClick (tab) {
      if (tab.label === '待审核') return this.getRuleForm('0')
      if (tab.label === '已审核') return this.getRuleForm('1')
      if (tab.label === '已拒绝') return this.getRuleForm('2')
      this.getRuleForm()
    },
    // 表头样式
    getRowClass () {
      return 'background:RGB(250, 250, 250)'
    },
    // 获取题库列表
    async getRuleForm (item) {
      let data = { page: this.page, pagesize: this.pagesize }
      if (item?.constructor === String || this.chkState) data.chkState = item
      if (item?.constructor === Object) data = { ...data, ...this.ruleForm }
      if (this.inputShow === true) {
        if (this.ruleForm?.subjectID) data = { ...data, subjectID: this.ruleForm.subjectID }
        if (this.ruleForm?.keyword) data = { page: this.page, pagesize: this.pagesize, keyword: this.ruleForm.keyword }
        if (this.ruleForm?.keyword && item?.constructor === String) data = { page: this.page, pagesize: this.pagesize, chkState: this.ruleForm.chkState, keyword: this.ruleForm.keyword }
        if (this.ruleForm?.keyword && this.ruleForm?.subjectID) data = { page: this.page, pagesize: this.pagesize, keyword: this.ruleForm.keyword, chkState: this.ruleForm.chkState }
        if (this.ruleForm?.keyword && item?.constructor === String && this.ruleForm?.subjectID) data = { page: this.page, pagesize: this.pagesize, keyword: this.ruleForm.keyword, chkState: item, subjectID: this.ruleForm.subjectID }
      }
      const { data: res } = await choice(data)
      this.page = +res.page
      this.pagesize = +res.pagesize
      this.pagesize = +res.pagesize
      this.counts = res.counts
      this.tableData = res.items
      this.title = `数据一共 ${res.counts} 条`
      this.tableData.forEach(item => {
        item.addDate = parseTime(item.addDate)
        item.question = html2Text(item.question)
        item.answer = html2Text(item.answer)
        item.difficulty = difficulty[difficulty.findIndex(val => val.value === +item.difficulty)].label
        item.questionType = questionType[questionType.findIndex(val => val.value === +item.questionType)].label
        item.publishState = publishType[publishType.findIndex(val => val.value === +item.publishState + 1)].label
        item.chkState = this.state[item.chkState]
      })
    },
    // 页数
    handleSizeChange (val) {
      this.pagesize = val
      this.getRuleForm()
    },
    // 当前页
    handleCurrentChange (val) {
      this.page = val
      this.getRuleForm()
    },
    // 审核弹框
    audit (row) {
      this.auditDialog = true
      this.auditId = row.id
    },
    // 审核弹框关闭
    dialogaudit () {
      this.auditDialog = false
      this.chkRemarks = ''
    },
    // 审核
    async clickAudit () {
      const data = {
        id: this.auditId,
        chkState: +this.chkState,
        chkRemarks: this.chkRemarks
      }
      const { data: res } = await choiceCheck(data)
      if (!res.success) return this.$message.error('审核失败')
      this.$message.success('审核成功')
      this.getRuleForm()
      this.auditDialog = false
      this.chkRemarks = ''
    },
    // 修改
    alter (row) {
      this.$router.push(`new?id=${row.id}`)
    },
    // 上下架
    clikcEmit (row) {
      if (row.chkState === '待审核') return this.$message.error('请审核!')
      const num = row.publishState === '已发布' ? 0 : 1
      const title = row.publishState === '已发布' ? '下架' : '上架'
      const data = {
        id: row.id,
        publishState: num
      }
      this.$confirm(`你确定${title}这道题目吗?`, '提示', { type: 'warning' }).then(async () => {
        await choicePublish(data)
        num === 1 ? (row.publishState = '已发布') : (row.publishState = '已下架')
        this.$message.success(`${title}成功`)
      }).catch(e => e)
    },
    // 删除
    async del (id) {
      const data = {
        id,
        choiceState: 0
      }
      this.$confirm('此操作将永久删除该题目, 是否继续?', '提示', { type: 'warning' }).then(async () => {
        await choiceAdd(data)
        this.getRuleForm()
        this.$message.success('删除成功')
      }).catch(e => e)
    },
    // 预览
    async preview (row) {
      const data = {
        id: row.id
      }
      const { data: res } = await detail(data)
      this.previewList = row
      this.previewList.options = res.options
      const num = this.previewList.options.filter(item => item.isRight === 1)
      this.optionsList = num[0].title
      this.previewDialog = true
    },
    // 预览 Dialog 数据回显
    previewListDialog () {
      this.previewDialog = false
      this.showVideo = false
    },
    // 获取数据
    async getList () {
      const { data: res } = await list({ page: 1, pagesize: 999 })
      const { data } = await getList({ page: 1, pagesize: 999 })
      const provincesAll = provinces()
      this.provincesList = provincesAll
      this.subjectName = res.items
      this.nameist = data.list
    },
    // 获取目录/标签
    async clickoPtion (id) {
      this.ruleForm.catalogID = ''
      this.ruleForm.tags = ''
      const data = { subjectID: id, page: 1, pagesize: 999 }
      const { data: simpleList } = await simple(data)
      const { data: getSimpleList } = await getSimple(data)
      this.simpleList = simpleList
      this.getSimpleList = getSimpleList
    },
    // 获取地区
    clickProvinces (name) {
      const res = citys(name)
      this.citysList = res
    },
    // 搜索
    search () {
      this.inputShow = true
      if (!this.ruleForm.subjectID && !this.ruleForm.keyword) return this.getRuleForm()
      this.getRuleForm(this.ruleForm)
    },
    // 清空
    empty () {
      this.inputShow = false
      this.$refs.ruleForm.resetFields()
      this.ruleForm.province = ''
    }
  }
}
</script>

<style scoped lang='scss'>
.container {
  font-size: 12px;
  color: pink;
}
.app-container {
  padding: 10px;
}
.elrow {
  margin-bottom: 10px;
}
.tabs {
  margin-bottom: 10px;
}
.row {
  margin-top: 15px;
  margin-bottom: 15px;
}
::v-deep .el-table_4_column_52 {
  text-align: center;
}
::v-deep .textarea {
  margin-top: 30px;
}
::v-deep .el-dialog__footer {
  text-align: right;
}
.elrow {
  margin-bottom: 20px;
}
.elradio {
  margin-top: 20px;
  margin-bottom: 20px;
}
</style>
